package com.budwk.app.sqfwV2.generator.centuryCity;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CommonParam;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.ExcelGenerateParam;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.ExcelRowDataParam;
import com.budwk.app.sqfwDoc.codeGeneratorV2.generate.BaseExcelGenerator;
import com.budwk.app.sqfwDoc.codeGeneratorV2.generate.ResultOfExcelDataInto;
import com.budwk.app.sqfwDoc.codeGeneratorV2.generate.ResultOfExcelGenerator;
import com.budwk.app.sqfwV2.dto.centuryCity.CenturyCityOldCarePdfDTO;
import com.budwk.app.sqfwV2.dto.centuryCity.CenturyCityProblemParamDTO;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.ProblemParamDTO;
import com.budwk.app.sqfwV2.dto.image.CenturyCityOldCareExcelImageConfigBO;
import com.budwk.app.sqfwV2.enums.HiddenDangerEnum;
import com.budwk.app.sqfwV2.enums.centuryCityOldCare.CenturyCityOldCareV2FileEnums;
import com.budwk.app.util.poiUtils.CommonFormOfficeUtils;
import com.budwk.app.util.poiUtils.excelPictureConfigBO.ExcelFileCreateParamBO;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author 东方祥云低代码1.1
 * @since 2024-06-06
 * <p>
 * 世纪城养老服务站巡查1.1 CenturyCityOldCare
 * 养老机构安全生产检查台账.xlsx
 */
public class ElderlyCareSafetyCheckLedgerExcelGenerator extends BaseExcelGenerator {

    private final ThreadLocal<ExcelCreateConfig> excelGenerateThreadLocal = ThreadLocal.withInitial(() -> null);

    private final Map<String, HiddenDangerEnumBO> hiddenDangerEnumBOMap;

    public ElderlyCareSafetyCheckLedgerExcelGenerator() {
        Map<String, HiddenDangerEnumBO> hiddenDangerEnumTempMap = Maps.newHashMap();
        for (HiddenDangerEnum value : HiddenDangerEnum.values()) {
            HiddenDangerEnumBO hiddenDangerEnumBO = new HiddenDangerEnumBO();
            BeanUtil.copyProperties(value, hiddenDangerEnumBO);
            hiddenDangerEnumTempMap.put(value.getCode(), hiddenDangerEnumBO);
        }
        this.hiddenDangerEnumBOMap = hiddenDangerEnumTempMap;
    }

    @Override
    protected void createExcelStart(ExcelGenerateParam excelGenerateParam) {
        ExcelCreateConfig excelConfig = excelGenerateParam.getExcelConfig();
        excelGenerateThreadLocal.set(excelConfig);
    }

    @Override
    protected void createExcelEnd(ExcelGenerateParam excelGenerateParam, ExcelFileCreateParamBO excelFileCreateParam, ResultOfExcelGenerator result) {
        excelGenerateThreadLocal.remove();
    }

    /**
     * 自定义excel的表头数据
     *
     * @param excelParam         excel参数整体参数map
     * @param excelGenerateParam 创建excel所提供的参数
     */
    @Override
    protected void customerPopularHeaderData(Map<String, Object> excelParam, ExcelGenerateParam excelGenerateParam) {

    }

    /**
     * 后端自定义维护表头数据
     *
     * @param excelParam         excel整体参数
     * @param excelGenerateParam 创建excel所提供的参数
     */
    @Override
    protected void customerPopularHeaderDataForAdmin(Map<String, Object> excelParam, ExcelGenerateParam excelGenerateParam) {

    }

    /**
     * @param excelParam         excel整体参数
     * @param excelGenerateParam 创建excel所提供的参数
     * @return 判断excel是否含有数据
     */
    @Override
    protected ResultOfExcelDataInto judgeExcelHaveDataBeforeErgodic(Map<String, Object> excelParam, ExcelGenerateParam excelGenerateParam) {
        return null;
    }

    /**
     * 根据行数据判断是否该条数据进入excel中
     *
     * @param rowDataParam       行数据
     * @param excelGenerateParam excel生成所提供的参数
     * @return 是/否
     */
    @Override
    protected boolean addRowDataCondition(ExcelRowDataParam rowDataParam, ExcelGenerateParam excelGenerateParam) {
        CenturyCityOldCarePdfDTO fieldDTO = (CenturyCityOldCarePdfDTO) rowDataParam.getAbstractCustomerPdfCreateField();
        return true;
    }

    /**
     * 用户自定义填充excel实体数据
     *
     * @param listMap            数据数据
     * @param excelGenerateParam 创建excel所需的参数
     */
    @Override
    protected void customerPopularSheetData(List<Map<String, Object>> listMap, ExcelGenerateParam excelGenerateParam) {

    }

    /**
     * 自定义填充excel中每一行的数据
     *
     * @param rowDataMap   当前行的数据Map
     * @param rowDataParam 所提供的当前行的数据
     */
    @Override
    protected void customerPopularRowDataMap(Map<String, Object> rowDataMap, ExcelRowDataParam rowDataParam) {
        CenturyCityOldCarePdfDTO fieldDTO = (CenturyCityOldCarePdfDTO) rowDataParam.getAbstractCustomerPdfCreateField();
        List<ProblemParamDTO> checkItemList = Optional.ofNullable(fieldDTO.getCheckItemList()).orElse(Lists.newArrayList());

        String isHydrantBlockedStr = "";    // excel灭火器是否被遮挡
        String isExtinguisherExpiredOrDamagedStr = "";  // excel灭火器是否过期
        StringBuilder foodSafetyStrSB = new StringBuilder();  //  食品安全情况
        StringBuilder rectificationSituationSB = new StringBuilder(); // 整改情况

        // 判断灭火器有无遮挡和灭火器是否过期
        String isExtinguisher = "";   // 是否配备灭火器
        String isHydrantBlocked = "";   // 灭火器是否被遮挡
        String isExtinguisherExpiredOrDamaged = ""; // 灭火器是否过期

        String rangeHoodCleanRecord = "";   // 是否定期清理台账
        String safeTipBadges = "";    // 卫生间或门槛处是否有安全提示标识
        for (ProblemParamDTO checkItem : checkItemList) {
            String fields = checkItem.getFields();
            String key = checkItem.getKey();
            String rectificationMeasure = checkItem.getRectificationMeasure();// 整改措施

            if (StringUtils.isNotBlank(rectificationMeasure)) {
                rectificationSituationSB = new StringBuilder(rectificationMeasure + ";");
            }

            if (fields.equals("isExtinguisher")) {
                isExtinguisher = key;
            }
            if (fields.equals("isHydrantBlocked")) {
                isHydrantBlocked = key;
            }
            if (fields.equals("isExtinguisherExpiredOrDamaged")) {
                isExtinguisherExpiredOrDamaged = key;
            }
            if (fields.equals("rangeHoodCleanRecord")) {
                rangeHoodCleanRecord = key;
            }
            if (fields.equals("safeTipBadges")) {
                safeTipBadges = key;
            }
        }

        if (isExtinguisher.equals("否")) {
            isHydrantBlockedStr = "未配备灭火器";
            isExtinguisherExpiredOrDamagedStr = "未配备灭火器";
        } else if (isExtinguisher.equals("是")) {
            if (isHydrantBlocked.equals("无")) {
                isHydrantBlockedStr = "已配备灭火器且未遮挡";
            } else if (isHydrantBlocked.equals("有")) {
                isHydrantBlockedStr = "灭火器被遮挡";
            }
            isExtinguisherExpiredOrDamagedStr = isExtinguisherExpiredOrDamaged;
        }

        // 食品安全问题
        List<CenturyCityProblemParamDTO> foodSaleForm = Optional.ofNullable(fieldDTO.getFoodSaleForm()).orElse(Lists.newArrayList());
        List<CenturyCityProblemParamDTO> foodServiceForm = Optional.ofNullable(fieldDTO.getFoodServiceForm()).orElse(Lists.newArrayList());
        List<CenturyCityProblemParamDTO> allFoodForm = Lists.newArrayList();
        allFoodForm.addAll(foodSaleForm);
        allFoodForm.addAll(foodServiceForm);

        for (CenturyCityProblemParamDTO foodItem : allFoodForm) {
            String riskCode = foodItem.getRiskCode();
            String rectificationTypeCode = foodItem.getRectificationTypeCode();
            String rectificationMeasure = foodItem.getRectificationMeasure();

            HiddenDangerEnumBO hiddenDangerItem = hiddenDangerEnumBOMap.get(riskCode);
            if (hiddenDangerItem != null && StringUtils.isNotBlank(rectificationTypeCode)) {
                String result = hiddenDangerItem.getResult();

                foodSafetyStrSB.append(result).append(";");
            }

            if (StringUtils.isNotBlank(rectificationMeasure)) {
                rectificationSituationSB.append(rectificationMeasure).append(";");
            }
        }

        rowDataMap.put("isHydrantBlocked", isHydrantBlockedStr);
        rowDataMap.put("isExtinguisherExpiredOrDamaged", isExtinguisherExpiredOrDamagedStr);

        if (StringUtils.isBlank(foodSafetyStrSB.toString())) foodSafetyStrSB = new StringBuilder("无");
        rowDataMap.put("foodSafety", foodSafetyStrSB.toString());

        if (StringUtils.isBlank(rectificationSituationSB.toString())) rectificationSituationSB = new StringBuilder("-");
        rowDataMap.put("rectificationSituation", rectificationSituationSB.toString());
        rowDataMap.put("rangeHoodCleanRecord", rangeHoodCleanRecord);
        rowDataMap.put("safeTipBadges", safeTipBadges);

        Boolean createExcelFileFlag = excelGenerateThreadLocal.get().getCreateExcelFileFlag();

        CommonParam createUserCommonParam = rowDataParam.getCreateUserCommonParam();
        String createUserSigUrl = createUserCommonParam.getCreateUserSigUrl();
        String createUserName = createUserCommonParam.getCreateUserName();
        if (StringUtils.isNotBlank(createUserSigUrl)) {

            if (createExcelFileFlag) {
                List<byte[]> bytes = CommonFormOfficeUtils.addPictureToByteList(createUserSigUrl, 1);
                rowDataMap.put("createUsernameSig", bytes);
            }
            rowDataMap.put("createUsername", "");
        } else {
            rowDataMap.put("createUsername", createUserName);
            rowDataMap.put("createUsernameSig", null);
        }

        if (createExcelFileFlag) {
            rowDataMap.put("inspectionPhotos", CommonFormOfficeUtils.addPictureToByteList(fieldDTO.getInspectionPhotos(), 1));
        }
    }

    /**
     * 后端生成excel时候自定义填充excel中每一行的数据
     *
     * @param rowDataMap   当前行的数据Map
     * @param rowDataParam 所提供的当前行的数据
     */
    @Override
    protected void customerPopularRowDataMapForAdmin(Map<String, Object> rowDataMap, ExcelRowDataParam rowDataParam) {
        CenturyCityOldCarePdfDTO fieldDTO = (CenturyCityOldCarePdfDTO) rowDataParam.getAbstractCustomerPdfCreateField();
    }

    /**
     * 在创建之前判断excel中是否含有数据
     *
     * @param excelParam         创建之前excel中已经填充的数据
     * @param excelGenerateParam 所提供的excel创建的所需要的数据
     * @return 结果
     */
    @Override
    protected ResultOfExcelDataInto judgeExcelHaveDataBeforeCreate(Map<String, Object> excelParam, ExcelGenerateParam excelGenerateParam) {
        List list = (List) excelParam.get("list");

        ResultOfExcelDataInto resultOfExcelDataInto = new ResultOfExcelDataInto();
        resultOfExcelDataInto.setExcelHaveDataFlag(!CollectionUtil.isEmpty(list));
        return resultOfExcelDataInto;
    }

    @Override
    protected String getTemplatePath(ExcelGenerateParam excelGenerateParam) {
        return CenturyCityOldCareV2FileEnums.elderlyCareInsSafetyInsLedgerExcel.getPath();
    }

    /**
     * 可以参照 {@link com.budwk.app.sqfw.enums.DownLoadFileNameEnum}
     *
     * @return 文件名名称
     */
    @Override
    public String getDownloadFileName(ExcelGenerateParam excelGenerateParam) {
        return CenturyCityOldCareV2FileEnums.elderlyCareInsSafetyCheckPdf.getDownloadFileName();
    }


    @Override
    protected Class<?> getImageConfigBO() {
        return CenturyCityOldCareExcelImageConfigBO.class;
    }

    /**
     * 允许用户在创建excel文件之前对配置进行修改
     *
     * @param excelFileCreateParamBO 创建excel的配置参数
     */
    @Override
    protected void completeExcelFileCreateParam(ExcelFileCreateParamBO excelFileCreateParamBO) {

    }
}
